package com.cloud.config;

import feign.RequestInterceptor;
import org.springframework.cloud.openfeign.FeignClientProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Author: Tangtao
 * @Date: 2022/5/2 23:25
 * @Description: Used for internal token transfer
 * @ClassName: FeignConfigToken
 */


@Configuration
public class FeignConfigToken extends FeignClientProperties.FeignClientConfiguration {


    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            assert attributes != null;
            HttpServletRequest request = attributes.getRequest();
            //透传请求header参数
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String values = request.getHeader(name);
                    if(name.equals("token")){
                        requestTemplate.header(name, values);
                    }
                }
            }

        };
    }



}
